package com.hboxs.asl.controller.app.product;

import com.hboxs.asl.Filter;
import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.Page;
import com.hboxs.asl.Pageable;
import com.hboxs.asl.controller.app.BaseController;
import com.hboxs.asl.entity.*;
import com.hboxs.asl.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by xxx on 2016/11/25.
 * 电商接口
 */
@Controller(value = "appProductController")
@RequestMapping(value = "/app/p")
public class ProductController extends BaseController {

    @Resource(name = "productCategoryServiceImpl")
    private ProductCategoryService productCategoryService;
    @Resource(name = "productServiceImpl")
    private ProductService productService;
    @Resource(name = "reviewServiceImpl")
    private ReviewService reviewService;
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "viewHistoryServiceImpl")
    private ViewHistoryService viewHistoryService;
    @Resource(name = "cartServiceImpl")
    private CartService cartService;

    /**
     * 商品列表
     *
     * @param pcId 分类id,不传显示所有商品
     * @return json
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public
    @ResponseBody
    Object list(Long pcId, Product.OrderType orderType,
                Pageable pageable) {


        ProductCategory pc = productCategoryService.find(pcId);

        Page page = productService.findPageGroup(
                pc, null, null, null, null, null, null, true, null, null, null, null, orderType, pageable
        );

        return JsonMessage.success(

                "totalPage", page.getTotalPages(),

                "pageNumber", page.getPageNumber(),

                "pageSize", page.getPageSize(),

                "total", page.getTotal(),

                "content", JsonMessage.optimiseObj(
                        page.getContent(),
                        "id", "image", "name", "price", "promotionPrice", "finalScore", "weight", "sales" ,"fakeSale"
                )

        );

    }

    /**
     * 商品详情
     *
     * @return json
     */
    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage detail(Long pId) {
        Product product = productService.find(pId);
        if (product == null) {
            return JsonMessage.error("找不到该商品");
        }
        // 详情只显示3个评论
        List<Filter> fs_r = new ArrayList<>();
        fs_r.add(Filter.eq("product.goods",product.getGoods()));
        List<Review> reviews = reviewService.findList(null, null, null, true, 3, fs_r, null);

        // 商品属性
        Map<String, String> attributeValue = new HashMap<>();
        Set<Attribute> attributes = product.getProductCategory().getAttributes();
        for (Attribute attribute : attributes) {
            String value = product.getAttributeValue(attribute);
            if (StringUtils.isEmpty(value)) {
                value = "";
            } else {
                value = value.replaceAll(",", " ");
            }
            attributeValue.put(attribute.getName(), value);
        }

        // 更新或添加商品浏览记录
        Member member = memberService.getCurrentByToken();
        if (member != null) {
            if (viewHistoryService.historyExists(member, product)) {
                Date date = new Date();
                ViewHistory viewHistory = viewHistoryService.getViewHistory(member, product);
                viewHistory.setDate(date);
                viewHistoryService.update(viewHistory);
            } else {
                ViewHistory vHistory = new ViewHistory(member, product, new Date());
                viewHistoryService.save(vHistory);
            }
        }

        //是否收藏该商品的标志
        int isFavor = 0;
        if (member != null && member.getFavoriteProducts().contains(product)) {
            isFavor = 1;
        }

        //购物车数量
        Cart cart = cartService.getCurrentByToken();
        int size = 0;
        if (cart!=null){
            size = cart.getCartItems().size();
        }

        // 商品促销活动
        Set<Promotion> promotions = product.getValidPromotions();

        return JsonMessage.success(

                "product", JsonMessage.optimiseObj(
                        product, "sn","name", "id", "price", "promotionPrice", "image", "sales", "stock",
                        "producer", "storage", "specificationValues.id#name" , "fakeSale", "merchant.id"
                )

                , "productImages", JsonMessage.optimiseObj(product.getProductImages(), "source")

                , "reviews", JsonMessage.optimiseObj(reviews, "content", "score", "member.id", "member.username", "member.name" , "member.avator")

                , "reviewsCount", reviews.size()

                , "attributeValue", attributeValue

//                , "specVal", product.getSpecValNames()

                , "isFavor", isFavor

                , "cartSize", size

                , "promotions" , JsonMessage.optimiseObj(promotions, "id" ,"title" ,"name")

        );
    }

    /**
     * 商品详情 - web查看评论
     *
     * @return JsonMessage
     */
    @RequestMapping(value = "/reviews", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage reviews(Long pId, Pageable pageable) {
        Product product = productService.find(pId);
        if (product == null) {
            return JsonMessage.error("找不到该商品");
        }

        Page page = reviewService.findPageGroup(null, product, null, true, pageable);

        return JsonMessage.success(

                "totalPage", page.getTotalPages(),

                "pageTotal", page.getTotal(),

                "pageNum", pageable.getPageNumber(),

                "pageSize", pageable.getPageSize(),

                "reviews", JsonMessage.optimiseObj(
                        page.getContent(), "score", "content", "createDate", "member.id", "member.username", "member.avator"
                ),

                "finalScore", product.getFinalScore(),

                "positiveRating", product.getPositiveRating()

        );
    }

    /**
     * 商品详情 - web查看内容
     *
     * @return string
     */
    @RequestMapping(value = "/product_detail", method = RequestMethod.GET)
    public String introduction(Long pId, ModelMap model) {
        Product product = productService.find(pId);
        if (product == null) {
            return "";
        }
        model.addAttribute("product", product);
        return "/app/product-detail";
    }

    /**
     * 规格页面
     *
     * @param pId 产品id
     */
    @RequestMapping(value = "/spec", method = RequestMethod.GET)
    public String spec(Long pId, ModelMap model) {
        model.addAttribute("product", productService.find(pId));
        return "/app/spec";
    }

}
